﻿using aier.business.logic;
using log4net;
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web.Http;

namespace aier.wx.api.selfhost.Controllers
{
    [RoutePrefix("api/ImageOcr")]
    public class ImageOcrController : ApiController
    {
        public IdentityCardOcrBll identityCardOcrBll { get; set; }

        private readonly string imgPathBase = System.Configuration.ConfigurationManager.AppSettings["imgPathBase"];

        public ILog log { get; set; }


        /// <summary>
        /// 识别身份证
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
		[FileSwagger(true)]
		//[Authorize]
		[ActionName(nameof(PostIdentityCard))]
        public async Task<IHttpActionResult> PostIdentityCard()
        {
            System.IO.Stream filestream = null;
            try
            {

                if (!Request.Content.IsMimeMultipartContent())
                {
                    throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
                }

                var provider = new MultipartMemoryStreamProvider();

                var task = await Request.Content.ReadAsMultipartAsync(provider);
                string filename = string.Empty;



                foreach (var item in provider.Contents)
                {
                    if (item.Headers.ContentDisposition.FileName != null)
                    {
                        filename = item.Headers.ContentDisposition.FileName.Trim('"');
                        long? filesize = item.Headers.ContentLength;
                        if (filesize.HasValue)
                        {
                            float fileSizeKb = GetKBSize(filesize.Value);
                            if (fileSizeKb > 4096)
                                throw new Exception("imageUrl's size should be less than 4096 KB");
                        }
                        filestream = await item.ReadAsStreamAsync();
                    }
                    // 获取FormData
                    else
                    {
                        ContentDispositionHeaderValue contentDisposition = item.Headers.ContentDisposition;
                        string formFieldName = contentDisposition.Name.Trim('"') ?? String.Empty;
                        string formFieldValue = await item.ReadAsStringAsync();
                        //log.Info(string.Concat(formFieldName, "-",formFieldValue));
                    }
                }

                var resResult = await identityCardOcrBll.GetIdentityCardByImg(filename, filestream);
                return Ok(resResult);
            }
            catch (Exception ex)
            {
                log.Error(ex.StackTrace, ex);
                return new ApiErrorResult(ex.Message, Request);
            }
            finally 
            {
                filestream?.Dispose();
            }
        }

        private float GetKBSize(long L)
        {
            float result = L / 1024.00F;
            return result;
        }

    }

    
}
